import {createStore} from 'vuex'
import Cookies from 'js-cookie'

const store = createStore({
    state() {  // 定义需要管理的数据 ， state 中定义的数据可以直接访问，但不能直接修改
        return {
            user: null, // 存储当前登录的用户名
            refresh: null , // 刷新令牌
            message: {  // 消息
                official: 0,
                letter: 0,
                notify: 0,
            } ,
        }
    },
    mutations: {  // 同步方法，相当于 vue 中 methods
        storeUserAndToken(state, {user, token, exp, refresh, remember}) {
            state.user = user;
            state.refresh = refresh;
            sessionStorage.setItem("RSS-USER", JSON.stringify(user));
            // 记住我的话，存储到 LocalStorage 中，否则存储到 sessionStorage 中
            if (remember) {
                localStorage.setItem("RSS-REFRESH-TOKEN", refresh);
            } else {
                sessionStorage.setItem("RSS-REFRESH-TOKEN", refresh);
            }
            // 设置 令牌，并设置过期时间
            Cookies.set("RSS-TOKEN", token, {expires: new Date(new Date().getTime() + exp * 1000)})
        },
        resetUserAndToken(state) {
            state.user = null ;
            state.refresh = null ;
            state.message = {official:0 , letter: 0, notify: 0} ;
            sessionStorage.removeItem("RSS-USER") ;
            localStorage.removeItem("RSS-REFRESH-TOKEN") ;
            sessionStorage.removeItem("RSS-REFRESH-TOKEN") ;
            Cookies.remove("RSS-TOKEN") ;
        },
        storeMessage(state, {official, letter, notify}) {
            state.message.official += official ;
            state.message.letter += letter ;
            state.message.notify += notify ;
        },
        modifyUserField(state, {name, value}) {
            state.user[name] = value ;
            sessionStorage.setItem("RSS-USER", JSON.stringify(state.user));
        },

    },
    getters: { // 相当于 vue 中 computed
        currentUser(state) {
            state.user = state.user ?? (sessionStorage.getItem("RSS-USER") != null ?  JSON.parse(sessionStorage.getItem("RSS-USER")) : null);
            return state.user
        },
        accessToken(state) {
            return Cookies.get("RSS-TOKEN");
        },
        refreshToken(state) {
            state.refresh = state.refresh == null ? (localStorage.getItem("RSS-REFRESH-TOKEN") ??  sessionStorage.getItem("RSS-REFRESH-TOKEN")) : state.refresh ;
            return state.refresh;
        },
        globalMessage(state) {
            return state.message ;
        }
    }
})

export default store;